package com.google.wave.extensions.code.eval;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 * {@code JavaxScriptCodeEvaluator} is a simple implementation of
 * {@link CodeEvaluator} that acts as a facade on top of the {@code
 * javax.script} package.
 *
 * @author schwardo@google.com (Don Schwarz)
 */
class JavaxScriptCodeEvaluator implements CodeEvaluator {
    private static ScriptEngineManager manager = new ScriptEngineManager();

    private final ScriptEngine engine;

    /**
     * Creates a {@code CodeEvaluator} that evaluates expressions in
     * the specified language.  The calling {@link ClassLoader} must
     * contain a service entry for a {@link ScriptEngineFactory} that
     * can create a {@link ScriptEngine} matching {@code language}.
     */
    public JavaxScriptCodeEvaluator(String language) {
	this.engine = manager.getEngineByName(language);
    }

    public CodeResult eval(String expr) {
	try {
	    Object result = engine.eval(expr);
	    return CodeResultFactory.getSuccessfulResult(result);
	} catch (ScriptException ex) {
            return CodeResultFactory.getErrorResult(ex.getCause(),
                                                    ex.getLineNumber(),
                                                    ex.getColumnNumber());
	}
    }
}
